<!DOCTYPE HTML>
<html>
<head>
  <title>My WebSocket</title>
</head>

<body>
<input id="text" type="text"/>
<button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message"></div>


</body>

<script type="text/javascript">

  let ws = null;
  //判断当前浏览器是否支持WebSocket
  if ('WebSocket' in window) {
    var userId = "admin";
    // ws = new WebSocket("ws://localhost:8081/ws/" + userId);
    // ws = new WebSocket("ws://localhost:8081/ws/");
    ws = new WebSocket("ws://127.0.0.1:8081/ws/" + userId);
  } else {
    alert('当前浏览器 Not support websocket')
  }

  //连接发生错误的回调方法
  ws.onerror = function () {
    setMessageInnerHTML("WebSocket连接发生错误");
  };

  //连接成功建立的回调方法
  ws.onopen = function (event) {
    console.log("ws调用连接成功回调方法")
    //ws.send("")
  }

  //接收到消息的回调方法
  ws.onmessage = function (message) {
    console.log("接收消息：" + message.data);
    if (typeof (message.data) == 'string') {
      setMessageInnerHTML(message.data);
    }
  }

  //ws连接断开的回调方法
  ws.onclose = function (e) {
    console.log("ws连接断开")
    //console.log(e)
    setMessageInnerHTML("ws close");
  }

  //将消息显示在网页上
  function setMessageInnerHTML(innerHTML) {
    console.log(innerHTML)
    document.getElementById('message').innerHTML += '接收的消息:' + innerHTML + '<br/>';
  }

  //关闭连接
  function closeWebSocket() {
    ws.close();
  }

  //发送消息
  function send(msg) {
    if (!msg) {
      msg = document.getElementById('text').value;
      document.getElementById('message').innerHTML += "发送的消息:" + msg + '<br/>';
      ws.send(msg);
    }
  }
</script>
</html>
